<?php
function wpjam_basic_ajax_response(){
	wpjam_verify_ajax_response();
}

function wpjam_weixin_robot_ajax_response(){
	wpjam_verify_ajax_response();
}

function wpjam_verify_ajax_response(){
	$action	= $_POST['page_action'];
	$data	= wp_parse_args($_POST['data']);

	if($action == 'submit'){
		$response = WPJAM_Verify::bind_user($data);

		if(is_wp_error($response)){
			wpjam_send_json($response);
		}else{
			wpjam_send_json(['errcode'=>0]);
		}
	}
}

function wpjam_verify_page(){
	?>
	<h2>WPJAM Basic</h2>
	
	<?php 

	$fields	= [
		'qrcode'	=> ['title'=>'二维码',	'type'=>'view'],
		'code'		=> ['title'=>'验证码',	'type'=>'text',	'description'=>'验证码10分钟内有效！'],
		'scene'		=> ['title'=>'scene',	'type'=>'hidden']
	];

	$response	= WPJAM_Verify::get_qrcode();

	if(is_wp_error($response)){

		echo '<div class="notice notice-error"><p>'.$response->get_error_message().'</p></div>';

		return;
	}else{
		echo '<p>1. 使用微信扫描下面的二维码获取验证码。<br />2. 将获取验证码输入提交即可！</p>';
	}

	$qrcode = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$response['ticket'];
	$fields['qrcode']['value']	= '<img srcset="'.$qrcode.' 2x" src="'.$qrcode.'" style="max-width:350px;" />';
	$fields['scene']['value']	= $response['scene'];

	wpjam_ajax_form([
		'fields'		=> $fields, 
		'action'		=> 'submit', 
		'submit_text'	=> '验证'
	]);

	?>

	<style type="text/css">
		.form-table th{width: 80px;}
	</style>

	<script type="text/javascript">
	jQuery(function($){
		$('body').on('page_action_success', function(e, response){
			if(response.page_action == 'submit'){
				window.location.reload();
			}
		});
	});
	</script>
	<?php
}